<script setup lang="ts">
import { hc } from "@/framework/vue/util/render";
import { FolderOpenOutlined } from "@ant-design/icons-vue";
import { computed, type PropType } from "vue";
import { omitNil } from "@/framework/util/objects";

defineOptions({ name: "folder-picker-input" });
const props = defineProps({
  value: { type: String as PropType<string | null | undefined> },
  placeholder: { type: String },
  disabled: { type: Boolean, default: () => undefined },
  readonly: { type: Boolean, default: () => undefined },
  allowClear: { type: Boolean, default: () => undefined },
  size: { type: String },
  bordered: { type: Boolean, default: () => undefined },
  addonBefore: { type: String },
  addonAfter: { type: String },
});

const emits = defineEmits({
  "update:value": (value: string) => true,
});
const handlePickFolder = async () => {
  const ret = await native.dialog.showOpenDirectoryDialog();
  if (!ret.canceled) {
    emits("update:value", ret.filePaths[0]);
  }
};

const inputProps = computed(() =>
  omitNil({
    value: props.value,
    placeholder: props.placeholder,
    disabled: props.disabled,
    readonly: props.readonly,
    allowClear: props.allowClear,
    size: props.size,
    bordered: props.bordered,
    addonBefore: props.addonBefore,
    addonAfter: props.addonAfter,
  }),
);

const buttonProps = computed(() =>
  omitNil({
    disabled: props.disabled,
    size: props.size,
  }),
);
</script>

<template>
  <div class="folder-picker-input">
    <a-input v-bind="inputProps" :value="value" @change="$emit('update:value', $event.target.value)" spellcheck="false" />
    <a-button v-bind="buttonProps" :icon="hc(FolderOpenOutlined)" @click="handlePickFolder" class="no-shrink" />
  </div>
</template>

<style lang="less">
.folder-picker-input {
  display: flex;
  align-items: center;
  column-gap: 10px;
}
</style>
